package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.USER_SIGN_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public Result signCount() {
        //获取用户id
        Long id = UserHolder.getUser().getId();
        //设置日期格式
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy-MM:"));
        String key=USER_SIGN_KEY+id+"-"+format;
        int month = now.getDayOfMonth();
        //从key中取出,返回的是10进制数字
        List<Long> s = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.signed(month )).valueAt(0)
        );
        if (s==null || s.isEmpty()){
            return Result.ok();
        }
        //取出数字
        Long l = s.get(0);
        if (l==null || l==0){
            return Result.ok();
        }
        //循环遍历
        int count=0;
        while (true){
            if ((l&1)==0){
                //未签，跳出循环
                break;
            }else {
                count++;
            }
            //数字右移一位
            l >>>= 1;
        }

        return Result.ok(count);
    }

    @Override
    public Result sign() {
        //获取用户id
        Long id = UserHolder.getUser().getId();
        //设置日期格式
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy-MM:"));
        String key=USER_SIGN_KEY+id+"-"+format;
        int month = now.getDayOfMonth();
        //setkey
        stringRedisTemplate.opsForValue().setBit(key,month-1,true);
        return Result.ok() ;
    }

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //检验验证码
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //验证手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号错误");
        }
        //验证码
        String code = stringRedisTemplate.opsForValue().get("login:code:" + phone);
        if (code==null || !code.equals(loginForm.getCode())){
            //不一致返回错误
            return Result.fail("验证码错误");
        }
        //查询用户信息
        User user = query().eq("phone", phone).one();
        if (user==null){
            //没有，创建新用户
            user=createuser(phone);
        }

        //生成token
        String token = UUID.randomUUID().toString(true);
        //将user转为map集合
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((filedname,filedvalue)->filedvalue.toString()));
        //在redis中存储
        stringRedisTemplate.opsForHash().putAll("login:user:"+token,userMap);
        //设置token有效期
        stringRedisTemplate.expire("login:user:"+token,30, TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);
    }

    private User createuser(String phone) {
        User user = new User();
        user.setNickName("user_"+RandomUtil.randomNumbers(5));
        user.setPhone(phone);
        save(user);
        return user;
    }

    //发送验证码
    @Override
    public Result send(String phone, HttpSession session) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号错误");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //将验证码返回redis
        stringRedisTemplate.opsForValue().set("login:code:"+phone,code);
        //发送验证码
        log.info("验证码已发送为：{}",code);
        return Result.ok();
    }
}
